/**
 * 青云门修真攻略 - 主要逻辑文件
 * 处理页面交互、数据渲染等功能
 */

// 全局变量
let currentSkillCategory = 'primary'; // 当前选中的技能分类
let currentPveTab = 'dungeons'; // 当前选中的PVE标签
let currentEquipmentTab = 'weapons'; // 当前选中的装备标签

/**
 * 页面初始化函数
 */
document.addEventListener('DOMContentLoaded', function() {
    console.log('青云门修真攻略页面加载完成');
    
    // 初始化各个模块
    initNavigation();
    initSkillsSection();
    initPveSection();
    initPvpSection();
    initEquipmentSection();
    
    // 添加平滑滚动效果
    addSmoothScrolling();
    
    console.log('所有模块初始化完成');
});

/**
 * 初始化导航功能
 */
function initNavigation() {
    const navLinks = document.querySelectorAll('.nav-link');
    
    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            // 移除所有active类
            navLinks.forEach(nav => nav.classList.remove('active'));
            
            // 添加active类到当前点击的链接
            this.classList.add('active');
            
            // 平滑滚动到目标部分
            const targetId = this.getAttribute('href');
            const targetSection = document.querySelector(targetId);
            
            if (targetSection) {
                targetSection.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        });
    });
}

/**
 * 初始化技能部分
 */
function initSkillsSection() {
    // 渲染技能分类按钮事件
    const categoryBtns = document.querySelectorAll('.category-btn');
    
    categoryBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            // 更新按钮状态
            categoryBtns.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            
            // 更新当前分类
            currentSkillCategory = this.getAttribute('data-category');
            
            // 重新渲染技能列表
            renderSkills(currentSkillCategory);
        });
    });
    
    // 初始渲染技能
    renderSkills(currentSkillCategory);
}

/**
 * 渲染技能列表
 * @param {string} category - 技能分类
 */
function renderSkills(category) {
    const skillsGrid = document.getElementById('skillsGrid');
    const skills = skillsData[category] || [];
    
    skillsGrid.innerHTML = skills.map(skill => `
        <div class="skill-card">
            <div class="skill-card-header">
                <div class="skill-name">${skill.name}</div>
                <div class="skill-type">${skill.type}</div>
                <div class="skill-level">${skill.level}</div>
            </div>
            <div class="skill-card-body">
                <div class="skill-description">${skill.description}</div>
                <div class="skill-stats">
                    <div class="skill-stat">
                        <div class="skill-stat-label">伤害</div>
                        <div class="skill-stat-value skill-damage">${skill.damage}</div>
                    </div>
                    <div class="skill-stat">
                        <div class="skill-stat-label">冷却</div>
                        <div class="skill-stat-value skill-cooldown">${skill.cooldown}秒</div>
                    </div>
                    <div class="skill-stat">
                        <div class="skill-stat-label">法力</div>
                        <div class="skill-stat-value skill-mana">${skill.manaCost}</div>
                    </div>
                    <div class="skill-stat">
                        <div class="skill-stat-label">范围</div>
                        <div class="skill-stat-value">${skill.range}</div>
                    </div>
                </div>
            </div>
        </div>
    `).join('');
}

/**
 * 初始化PVE部分
 */
function initPveSection() {
    // PVE标签切换事件
    const pveTabs = document.querySelectorAll('.pve-tab');
    
    pveTabs.forEach(tab => {
        tab.addEventListener('click', function() {
            // 更新标签状态
            pveTabs.forEach(t => t.classList.remove('active'));
            this.classList.add('active');
            
            // 更新当前标签
            currentPveTab = this.getAttribute('data-tab');
            
            // 重新渲染PVE内容
            renderPveContent(currentPveTab);
        });
    });
    
    // 初始渲染PVE内容
    renderPveContent(currentPveTab);
}

/**
 * 渲染PVE内容
 * @param {string} tab - PVE标签类型
 */
function renderPveContent(tab) {
    const pveContent = document.getElementById('pveContent');
    
    switch(tab) {
        case 'dungeons':
            renderDungeons(pveContent);
            break;
        case 'bosses':
            renderBosses(pveContent);
            break;
        case 'leveling':
            renderLeveling(pveContent);
            break;
        default:
            pveContent.innerHTML = '<p>内容加载中...</p>';
    }
}

/**
 * 渲染副本攻略
 * @param {HTMLElement} container - 容器元素
 */
function renderDungeons(container) {
    const dungeons = pveData.dungeons;
    
    container.innerHTML = `
        <div class="dungeons-grid">
            ${dungeons.map(dungeon => `
                <div class="guide-card">
                    <div class="guide-card-header">
                        <div class="guide-title">${dungeon.name}</div>
                        <div class="guide-meta">
                            <span class="difficulty-badge difficulty-${dungeon.difficulty === '困难' ? 'hard' : dungeon.difficulty === '中等' ? 'medium' : 'easy'}">
                                ${dungeon.difficulty}
                            </span>
                            <span class="guide-rewards">${dungeon.rewards}</span>
                        </div>
                    </div>
                    <div class="guide-card-body">
                        <div class="guide-summary">${dungeon.strategy}</div>
                        <div class="strategy-tips">
                            <div class="strategy-tips-title">攻略要点</div>
                            <ul class="strategy-tips-list">
                                ${dungeon.tips.map(tip => `<li>${tip}</li>`).join('')}
                            </ul>
                        </div>
                        <div class="guide-tags">
                            ${dungeon.tags.map(tag => `<span class="guide-tag">${tag}</span>`).join('')}
                        </div>
                    </div>
                </div>
            `).join('')}
        </div>
    `;
}

/**
 * 渲染BOSS攻略
 * @param {HTMLElement} container - 容器元素
 */
function renderBosses(container) {
    const bosses = pveData.bosses;
    
    container.innerHTML = `
        <div class="bosses-grid">
            ${bosses.map(boss => `
                <div class="guide-card">
                    <div class="guide-card-header">
                        <div class="guide-title">${boss.name}</div>
                        <div class="guide-meta">
                            <span class="difficulty-badge difficulty-hard">${boss.difficulty}</span>
                            <span class="guide-rewards">血量: ${boss.hp}</span>
                        </div>
                    </div>
                    <div class="guide-card-body">
                        <div class="guide-summary">${boss.strategy}</div>
                        <div class="boss-phases">
                            <h4 style="color: var(--primary-color); margin-bottom: 1rem;">战斗阶段</h4>
                            ${boss.phases.map(phase => `
                                <div class="strategy-tips" style="margin-bottom: 1rem;">
                                    <div class="strategy-tips-title">第${phase.phase}阶段: ${phase.description}</div>
                                    <div style="color: var(--text-secondary); margin-top: 0.5rem;">${phase.tactics}</div>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                </div>
            `).join('')}
        </div>
    `;
}

/**
 * 渲染练级指南
 * @param {HTMLElement} container - 容器元素  
 */
function renderLeveling(container) {
    const levelingGuides = pveData.leveling;
    
    container.innerHTML = `
        <div class="leveling-grid">
            ${levelingGuides.map(guide => `
                <div class="guide-card">
                    <div class="guide-card-header">
                        <div class="guide-title">${guide.level}</div>
                        <div class="guide-meta">
                            <span class="guide-rewards">经验: ${guide.experience}</span>
                        </div>
                    </div>
                    <div class="guide-card-body">
                        <div class="leveling-info">
                            <div class="stat-item">
                                <span class="stat-label">推荐地点</span>
                                <span class="stat-value">${guide.location}</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">怪物类型</span>
                                <span class="stat-value">${guide.monsters}</span>
                            </div>
                        </div>
                        <div class="guide-summary">${guide.tips}</div>
                    </div>
                </div>
            `).join('')}
        </div>
    `;
}

/**
 * 初始化PVP部分
 */
function initPvpSection() {
    renderPvpStrategies();
}

/**
 * 渲染PVP策略
 */
function renderPvpStrategies() {
    const strategyGrid = document.getElementById('strategyGrid');
    const strategies = pvpData.strategies;
    
    strategyGrid.innerHTML = strategies.map(strategy => `
        <div class="strategy-card">
            <div class="strategy-header">
                <div>
                    <div class="strategy-title">${strategy.title}</div>
                    <div class="strategy-vs">VS ${strategy.opponent}</div>
                </div>
                <div class="win-rate">
                    <div class="win-rate-label">胜率</div>
                    <div class="win-rate-value">${strategy.winRate}</div>
                </div>
            </div>
            <div class="strategy-content">${strategy.content}</div>
            <div class="strategy-tips">
                <div class="strategy-tips-title">战术要点</div>
                <ul class="strategy-tips-list">
                    ${strategy.tips.map(tip => `<li>${tip}</li>`).join('')}
                </ul>
            </div>
        </div>
    `).join('');
}

/**
 * 初始化装备部分
 */
function initEquipmentSection() {
    // 装备标签切换事件
    const equipmentTabs = document.querySelectorAll('.equipment-tab');
    
    equipmentTabs.forEach(tab => {
        tab.addEventListener('click', function() {
            // 更新标签状态
            equipmentTabs.forEach(t => t.classList.remove('active'));
            this.classList.add('active');
            
            // 更新当前标签
            currentEquipmentTab = this.getAttribute('data-tab');
            
            // 重新渲染装备内容
            renderEquipmentContent(currentEquipmentTab);
        });
    });
    
    // 初始渲染装备内容
    renderEquipmentContent(currentEquipmentTab);
}

/**
 * 渲染装备内容
 * @param {string} tab - 装备标签类型
 */
function renderEquipmentContent(tab) {
    const equipmentContent = document.getElementById('equipmentContent');
    const equipments = equipmentData[tab] || [];
    
    equipmentContent.innerHTML = `
        <div class="equipment-grid">
            ${equipments.map(equipment => `
                <div class="equipment-card">
                    <div class="equipment-card-header">
                        <div class="equipment-name">${equipment.name}</div>
                        <div class="equipment-type">${equipment.type}</div>
                        <span class="equipment-rarity rarity-${equipment.rarity}">
                            ${getRarityText(equipment.rarity)}
                        </span>
                    </div>
                    <div class="equipment-card-body">
                        <div class="equipment-stats">
                            ${Object.entries(equipment.stats).map(([key, value]) => `
                                <div class="equipment-stat">
                                    <span class="equipment-stat-name">${getStatName(key)}</span>
                                    <span class="equipment-stat-value">+${value}</span>
                                </div>
                            `).join('')}
                        </div>
                        <div class="equipment-source">
                            <div class="equipment-source-label">获取途径</div>
                            <div class="equipment-source-value">${equipment.source}</div>
                        </div>
                        <div class="guide-summary">${equipment.description}</div>
                    </div>
                </div>
            `).join('')}
        </div>
    `;
}

/**
 * 获取稀有度文本
 * @param {string} rarity - 稀有度等级
 * @returns {string} 稀有度文本
 */
function getRarityText(rarity) {
    const rarityMap = {
        'common': '普通',
        'rare': '稀有', 
        'epic': '史诗',
        'legendary': '传说'
    };
    return rarityMap[rarity] || '普通';
}

/**
 * 获取属性名称
 * @param {string} statKey - 属性键名
 * @returns {string} 属性中文名称
 */
function getStatName(statKey) {
    const statMap = {
        'attack': '攻击力',
        'defense': '防御力',
        'magicDefense': '法术防御',
        'hp': '生命值',
        'mana': '法力值',
        'critRate': '暴击率',
        'critDamage': '暴击伤害',
        'spellPower': '法术强度',
        'manaRegen': '法力回复',
        'cooldownReduction': '冷却缩减'
    };
    return statMap[statKey] || statKey;
}

/**
 * 添加平滑滚动效果
 */
function addSmoothScrolling() {
    // 监听滚动事件，更新导航状态
    window.addEventListener('scroll', function() {
        const sections = document.querySelectorAll('.section');
        const navLinks = document.querySelectorAll('.nav-link');
        
        let currentSection = '';
        
        sections.forEach(section => {
            const sectionTop = section.offsetTop - 100;
            const sectionHeight = section.offsetHeight;
            
            if (window.scrollY >= sectionTop && window.scrollY < sectionTop + sectionHeight) {
                currentSection = section.getAttribute('id');
            }
        });
        
        // 更新导航状态
        navLinks.forEach(link => {
            link.classList.remove('active');
            if (link.getAttribute('href') === `#${currentSection}`) {
                link.classList.add('active');
            }
        });
    });
}

/**
 * 工具函数：显示加载状态
 * @param {HTMLElement} container - 容器元素
 */
function showLoading(container) {
    container.innerHTML = `
        <div class="loading">
            <div class="loading-spinner"></div>
        </div>
    `;
}

/**
 * 工具函数：显示错误信息
 * @param {HTMLElement} container - 容器元素
 * @param {string} message - 错误信息
 */
function showError(container, message) {
    container.innerHTML = `
        <div style="text-align: center; padding: 2rem; color: var(--text-muted);">
            <p>❌ ${message}</p>
        </div>
    `;
}

// 添加一些交互效果
document.addEventListener('DOMContentLoaded', function() {
    // 为工具按钮添加点击效果
    const toolBtns = document.querySelectorAll('.tool-btn');
    
    toolBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            // 简单的点击反馈
            this.style.transform = 'scale(0.95)';
            setTimeout(() => {
                this.style.transform = 'scale(1)';
            }, 150);
            
            // 这里可以添加具体的工具功能
            alert('功能开发中，敬请期待！');
        });
    });
});